package com.example.mybaseapp.ui

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.SurfaceTexture
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraManager
import android.os.Bundle
import android.text.TextUtils
import android.util.Size
import android.view.LayoutInflater
import android.view.TextureView
import android.view.ViewGroup
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.lib_base.BaseActivity
import com.example.mybaseapp.R
import com.example.mybaseapp.databinding.ActivityCamerasBinding
import com.example.mybaseapp.databinding.ItemPackReceiverBinding
import com.example.mybaseapp.util.CameraUtil

class CamerasActivity : BaseActivity<ActivityCamerasBinding>(), TextureView.SurfaceTextureListener {
    private val cameras = mutableListOf<CameraData>()
    private val myAdapter = CameraSimpleAdapter(this@CamerasActivity, cameras)
    private lateinit var cameraManager: CameraManager
    private lateinit var size: Size
    private lateinit var previewSurfaceTexture: SurfaceTexture
    private var currentCameraId: CameraData? = null


    override fun onViewInit() {
        initMyView()
    }

    private fun initMyView() {
        binding.btnInvalidate.setOnClickListener {
            binding.myview.invalidate()
        }
        binding.btnRequestLayout.setOnClickListener {
            binding.myview.requestLayout()
        }
    }

    private fun initCameraUtil() {
        CameraUtil(this).findLogicCameraId()
    }

    private fun initCamera() {
        cameraManager = getSystemService(CameraManager::class.java)
        val cameraIdList = cameraManager.cameraIdList

        val deviceLevel = CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL
        cameraIdList.forEach { id ->
            val cameraCharacteristics = cameraManager.getCameraCharacteristics(id)
            if (cameraCharacteristics[CameraCharacteristics.LENS_FACING] == CameraCharacteristics.LENS_FACING_BACK) {
                cameras.add(CameraData(id, cameraCharacteristics[CameraCharacteristics.SENSOR_ORIENTATION]!!,cameraCharacteristics))
            } else if (cameraCharacteristics[CameraCharacteristics.LENS_FACING] == CameraCharacteristics.LENS_FACING_FRONT) {
                cameras.add(CameraData(id, cameraCharacteristics[CameraCharacteristics.SENSOR_ORIENTATION]!!,cameraCharacteristics))
            }
//            else if(){//广角摄像头
//
//            }
        }
        myAdapter.notifyDataSetChanged()
    }


    private fun initRecyclerView() {
        findViewById<RecyclerView>(R.id.recyclerview).apply {
            layoutManager = LinearLayoutManager(this@CamerasActivity)
            adapter = myAdapter
        }
    }
    var WIDTH = 1920

    var HEIGHT = 1080
    private fun openCamera(cameraData: CameraData) {
        val cameraCharacteristics = cameraData.mCameraCharacteristics
        if (this::cameraManager.isInitialized && cameraCharacteristics != null) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                return
            }
//            try {
//                size = getOptimalSize(cameraCharacteristics, SurfaceTexture::class.java, WIDTH, HEIGHT)!!
//            }catch (e: Exception){}
//            previewSurfaceTexture.setDefaultBufferSize(size.width, size.height)
//            cameraManager.openCamera(cameraData, CameraStateCallback(), null)
//            (activity as MainActivity).currentCameraId = cameraData
        }
    }

//    inner class CameraStateCallback : CameraDevice.StateCallback() {
//        override fun onOpened(camera: CameraDevice) {
//            cameraDevice = camera
//            isCameraOpen = true
//            startPreview((activity as MainActivity).isPush())
//        }
//
//        override fun onDisconnected(camera: CameraDevice) {
//            isCameraOpen = false;
//        }
//
//        override fun onError(camera: CameraDevice, error: Int) {
//            camera.close()
//        }
//
//        override fun onClosed(camera: CameraDevice) {
//            super.onClosed(camera)
//            isCameraOpen = false
//        }
//    }
//
//    public fun startPreview(pushFlag: Boolean) {
//        if (!isCameraOpen) {
//            return
//        }
//        var rotation = if ((activity as MainActivity).currentCameraId == backCameraId) backRotation else frontRotation
//
//        if((activity as MainActivity).changeScreenPage == 1){//横屏状态下，角度修改
//            rotation = 0 //当横屏时，无论是用前置摄像头还是后置摄像头，旋转度数都给0
//        }
//        previewSurfaceTexture.setDefaultBufferSize(size.width, size.height)
//        val previewSurface = Surface(previewSurfaceTexture)
//        val encodeTask = (activity as MainActivity).encodeTask()
//        var dataSurface :Surface? = null
//        if(pushFlag) dataSurface = encodeTask.initMediaCodec(WIDTH, HEIGHT, rotation, pushFlag)
//        //录屏/相机来回切换的时候重新push
//        (activity as MainActivity).resumePush()
//        var outputs : List<Surface?>
//        if(pushFlag){
//            outputs = listOf(dataSurface, previewSurface)
//        }else{
//            outputs = listOf(previewSurface)
//        }
//
//        try {
//            cameraDevice.createCaptureSession(outputs, object : CameraCaptureSession.StateCallback() {
//                override fun onConfigureFailed(session: CameraCaptureSession) {
//
//                }
//
//                override fun onConfigured(session: CameraCaptureSession) {
//                    try {
//                        if (isCameraOpen) {
//                            cameraSession = session
//                            requestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)
//                            if(pushFlag)requestBuilder.addTarget(dataSurface!!)
//                            requestBuilder.addTarget(previewSurface)
//                            val request = requestBuilder.build()
//                            cameraSession.setRepeatingRequest(request, object : CameraCaptureSession.CaptureCallback() {}, null)
//                        }
//
//                    } catch (e: Exception) {
//                        e.printStackTrace()
//                    }
//                }
//            }, null)
//        } catch (e: Exception) {
//            e.printStackTrace()
//        }
//    }
//
//    private fun getOptimalSize(cameraCharacteristics: CameraCharacteristics, clazz: Class<*>, maxWidth: Int, maxHeight: Int): Size? {
//        val aspectRatio = maxWidth.toFloat() / maxHeight
//        val streamConfigurationMap = cameraCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
//        val supportedSizes = streamConfigurationMap?.getOutputSizes(clazz)
//        if (supportedSizes != null) {
//            for (size in supportedSizes) {
//                if (size.width.toFloat() / size.height == aspectRatio && size.height <= maxHeight && size.width <= maxWidth) {
//                    return size
//                }
//            }
//        }
//        return null
//    }
//
    inner class CameraSimpleAdapter(private val context: Context, private val itemList: MutableList<CameraData>) : RecyclerView.Adapter<CameraSimpleAdapter.ViewHolder>() {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val binding: ItemPackReceiverBinding = DataBindingUtil.inflate(LayoutInflater.from(parent.context), R.layout.item_pack_receiver, parent, false)
            return ViewHolder(binding)
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val item = itemList[position]
            holder.bind(item,position)
        }

        override fun getItemCount(): Int {
            return itemList.size
        }

        inner class ViewHolder(private val binding: ItemPackReceiverBinding) : RecyclerView.ViewHolder(binding.root) {

            fun bind(item: CameraData, position: Int) {
                binding.txContent.setTag(R.id.key1,item)
                binding.txContent.setTag(R.id.key2,position)
                binding.txContent.text = "ID：${item.id} rotation：${item.rotation}"
                binding.txContent.setOnClickListener {
                    val cameraData = it.getTag(R.id.key1) as CameraData

                    openCamera(cameraData)
                }
                binding.executePendingBindings()
            }
        }
    }

    inner class CameraData(val id:String,val rotation:Int,val mCameraCharacteristics:CameraCharacteristics)

    override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) {
        previewSurfaceTexture = surface
        var cameraId : CameraData
        if(this@CamerasActivity.currentCameraId == null){
            cameraId = if(TextUtils.isEmpty(cameras[0].id)) cameras[0] else cameras[1]
        } else{
            cameraId = currentCameraId!!
        }
        if (!TextUtils.isEmpty(cameraId.id)) {
            openCamera(cameraId)
        }
    }

    override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {
        TODO("Not yet implemented")
    }

    override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
        TODO("Not yet implemented")
    }

    override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {
        TODO("Not yet implemented")
    }
}